"use strict";

const Service = require("egg").Service;

class RoomService extends Service {
    /**
     * 获取教室列表
     */
    async readList() {
        let sql = "select * from room";
        let res = await this.app.mysql.query(sql);
        return res;
    }

    /**
     * 根据教室id，查找某个教室
     * @param {string} id 教室id
     */
    async find(id) {
        let sql = "select * from room where id = ? limit 0, 1";
        let params = [id];
        let res = await this.app.mysql.query(sql, params);
        return res[0];
    }

    /**
     * 根据教室名称，查找某个教室
     * @param {string} name 教室名称
     */
    async findByName(name) {
        let sql = "select * from room where name = ? limit 0, 1";
        let params = [name];
        let res = await this.app.mysql.query(sql, params);
        return res[0];
    }

    /**
     * 添加一个教室
     * @param {object} param0 教室对象
     */
    async save({ name }) {
        // 教室是否存在
        const room = await this.findByName(name);
        if (room) {
            this.ctx.cast(403, "该教室名称已存在");
        }
        // 添加教室
        let sql = "insert into room (id, name) values (?, ?)";
        let params = [this.ctx.helper.uuid(), name];
        let res = await this.app.mysql.query(sql, params);
        return {
            id: res.insertId,
            rows: res.affectedRows,
        };
    }

    /**
     * 删除一个教室
     * @param {*} id
     */
    async remove(id) {
        // 教室不存在
        const room = await this.find(id);
        if (!room) {
            this.ctx.cast(404, "该教室不存在");
        }
        // 删除教室
        let sql = "delete from room where id = ?";
        let params = [id];
        let res = await this.app.mysql.query(sql, params);
        return {
            rows: res.affectedRows,
        };
    }
}

module.exports = RoomService;
